<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .tree ul {
  padding-left: 20px;
  list-style: none;
}

.tree-node {
  cursor: pointer;
}

.tree-node:before {
  content: '';
  display: inline-block;
  width: 16px;
  height: 16px;
  margin-right: 6px;
  background-image: url(../images/tree-arrow.png);
  background-repeat: no-repeat;
  background-position: center center;
  vertical-align: middle;
}

.tree-node.collapsed:before {
  transform: rotate(90deg);
}

.tree-node.has-children:before {
  content: '';
  display: inline-block;
  width: 16px;
  height: 16px;
  margin-right: 6px;
  background-image: url(../images/tree-folder.png);
  background-repeat: no-repeat;
  background-position: center center;
  vertical-align: middle;
}

.tree-node.has-children.collapsed:before {
  transform: rotate(90deg);
}

.tree-node.selected {
  background-color: #f0f0f0;
}

.tree-node.selected:before {
  background-image: url(../images/tree-selected.png);
}
    </style>
</head>
<body>
    <div class="tree">
        <ul>
          <li>
            <span class="tree-node">节点1</span>
            <ul>
              <li><span class="tree-node">子节点1</span></li>
              <li><span class="tree-node">子节点2</span></li>
            </ul>
          </li>
          <li><span class="tree-node">节点2</span></li>
          <li><span class="tree-node">节点3</span></li>
        </ul>
      </div>
</body>
<script>
    // 获取所有节点
const nodes = document.querySelectorAll('.tree-node');
nodes.forEach(node => {
  // 点击展开/折叠子节点
  node.addEventListener('click', e => {
    const parent = e.target.parentNode;
    if (parent.classList.contains('has-children')) {
      parent.classList.toggle('collapsed');
    }
  });

  // 选中节点
  node.addEventListener('mousedown', e => {
    const selectedNodes = document.querySelectorAll('.selected');
    selectedNodes.forEach(node => {
      node.classList.remove('selected');
    });
    e.target.classList.add('selected');
  });
});

// 设置初始状态
const tree = document.querySelector('.tree');
tree.querySelectorAll(':scope > ul > li').forEach(node => {
  if (node.querySelector(':scope > ul')) {
    node.classList.add('has-children');
    node.classList.add('collapsed');
  }
});
</script>
</html>